package org.amos.msg.platform.email;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.google.common.base.Throwables;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.amos.core.basic.utils.AmosUtils;
import org.amos.msg.model.EmailContentModel;
import org.amos.msg.params.PushMsgParam;
import org.amos.msg.platform.AbstractMsgPlatform;

@Slf4j
public class EmailMsgPlatform extends AbstractMsgPlatform<EmailMsgConfig> {

    private MailAccount client;

    public EmailMsgPlatform(String id, EmailMsgConfig config) {
        super(id, config);
    }

    @Override
    protected void initClient() {
        client = AmosUtils.copy(config, MailAccount.class);
        try {
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            client.setCustomProperty("mail.smtp.ssl.socketFactory", sf);
            if (config.getTimeout() <= 0) {
                client.setTimeout(25000);
            }
            if (config.getConnectionTimeout() <= 0) {
                client.setConnectionTimeout(25000);
            }
        } catch (Exception e) {
            log.error("EmailHandler#getAccount fail!{}", Throwables.getStackTraceAsString(e));
        }
    }

    @Override
    public Boolean push(PushMsgParam param) {
        EmailContentModel emailContentModel = (EmailContentModel) param.getContentModel();
        try {
            MailUtil.send(client, param.getReceiver(), emailContentModel.getTitle(),
                    emailContentModel.getContent(), true, null);
        } catch (Exception e) {
            log.error("EmailHandler#handler fail!{},params:{}", Throwables.getStackTraceAsString(e), param);
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}
